<?php
namespace app\admin\controller;
use app\admin\controller\Base;
class Category extends Base
{
    
    private $obj;  
    
     public function _initialize() {
         $this->obj=model("Category");
     }
    //分类展示
    public function index(){
      $parentId=input('get.parent_id', 0 , 'intval'); 
      $categorys=  $this->obj->getFirstCategorys($parentId);
        return $this->fetch('',[
           'categorys' =>$categorys,
            
        ]);
    }
    
    //添加分类
    public function add(){
        $categorys=$this->obj->getNormalFirstCategory();
      return $this->fetch("add",[
          "categorys"=>$categorys
      ]);  
    }
    
    //添加测试
    public function save(){
       if(!request()->isPost()){
           $this->error("非法请求");
        }
        $data=input('post.');//表单传值
        //validate检测
        $validate= validate('Category');
        if(!$validate->scene("add")->check($data)){
            $this->error($validate->getError());
        }
        
        //执行更新操作
        if(!empty($data['id'])){
            return $this->update($data);
        }
        
        //把数据提交给model层完成数据的添加
       $res=$this->obj->add($data);
       if($res){
           $this->success("新增成功");
       }else{
           $this->error("新增失败");
       }
    }
    
    
    //修改分类
    public function edit($id=0){
        if(intval($id)<0){
            $this->error("参数不合法");
        }
        $category=$this->obj->get($id);
        $categorys=$this->obj->getNormalFirstCategory();
        
      return $this->fetch('',[
        'category'=>$category,  
        'categorys'=>$categorys,
      ]);  
    }
   
    //更新
    public function update($data){
        $res=$this->obj->save($data,['id'=>intval($data['id'])]);
        if($res){
            $this->success("更新成功");
        }else{
           
            $this->error("更新失败");
        }
        
    }
    
    //排序 
    public function listorder($id, $listorder){
       $res=$this->obj->save(["listorder"=>$listorder],["id"=>$id]);
       if($res){
           $this->result($_SERVER['HTTP_REFERER'],1,'success');
       }else{
           $this->result($_SERVER['HTTP_REFERER'],0,'更新失败');
       }
    }
    
    //修改状态或删除
    public function status(){
       if(!request()->isGet()){
           $this->error("非法请求");
       }
       //get传值
       $data=input("get.");
       $validate= validate('Category');
        if(!$validate->scene("status")->check($data)){
            $this->error($validate->getError());
        }
        $res=$this->obj->save(["status"=>$data['status']],["id"=>$data['id']]);
        if($res){
            $this->success("更新成功");
        }else{
             $this->error("更新失败");
        }
        
    }
    
}

